﻿using Furion.Authorization;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Project2.Web.Core;

public class JwtHandler : AppAuthorizeHandler
{

    public override async Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
    {
        return await CheckPermission(httpContext);
    }

    /// <summary>
    /// Use DataBase Query For Permission
    /// </summary>
    /// <returns></returns>
    private async Task<bool> CheckPermission(DefaultHttpContext httpContext)
    {
        // Get SecurityDefine
        var securityDefineAttribute = httpContext.GetMetadata<AppAuthorizeAttribute>();
        if (securityDefineAttribute == null) return await Task.FromResult(true);

        // 此处直接抛出异常无法到达下面的判断代码
        var testPolicies = securityDefineAttribute.Policies;
        if(testPolicies== null|| testPolicies.Length <= 0) return await Task.FromResult(true);

        return await Task.FromResult(true);
    }
}